package tictactoe;

import java.awt.Point;
import tictactoe.util.Constants;

/**
 *
 * @author buya
 */
public class Game {

    private Player cross, circle;
    private int turn;
    private int playing;
    private Desk desk;

    public Game(Player cross, Player circle) {
        this(cross, circle, Constants.CROSS);
    }

    public Game(Player cross, Player circle, int playing) {
        desk = new Desk(16, 16);
        this.cross = cross;
        this.circle = circle;
        this.playing = playing;
        turn = 0;
    }

    public void startGame() {
        playing = Constants.CROSS;
        turn = 0;
    }

    public boolean turn(Point where) {
        if (turn(playing, where)) {
            turn++;
            if (playing == Constants.CIRCLE) {
                playing = Constants.CROSS;
            } else {
                playing = Constants.CIRCLE;
            }
            return true;
        }

        return false;
    }

    public Player getCross() {
        return cross;
    }
    
    public Player getCircle() {
        return circle;
    }

    public Player getWinnerPlayer() {
        switch(desk.getWinner()) {
            case Desk.CIRCLE:
                return circle;
            case Desk.CROSS:
                return cross;
            default:
                return null;
        }
    }

    public int getWinner() {
        return desk.getWinner();
    }

    public int getTurnCount() {
        return turn;
    }

    public int getPlaying() {
        return playing;
    }

    public Player whoseTurn() {
        if (playing == Constants.CROSS) return cross;
        if (playing == Constants.CIRCLE) return circle;

        return null;
    }

    public Desk getDeskCopy() {
        return (Desk)desk.clone();
    }

    private boolean turn(int player, Point where) {
        if (desk.canPlace(where)) {
            return desk.add(player, where);
        } else {
            return false;
        }
    }
}
